package com.example.sangong.utils;

import cn.hutool.core.util.StrUtil;
import com.example.sangong.entity.Player;
import com.example.sangong.entity.UserPlayRecord;
import com.example.sangong.req.CalCreditParamReq;
import com.example.sangong.resp.UserPlayRecordResp;

import java.util.*;
import java.util.stream.Collectors;

public class UserPlayRecordDbUtils {
    private static Map<String, List<UserPlayRecord>> roomPlayRecord = new HashMap<>();

    public static void add(String roomNo, List<UserPlayRecord> dataList) {
        List<UserPlayRecord> userPlayRecords = Optional.ofNullable(roomPlayRecord.get(roomNo)).orElse(new ArrayList<>());
        userPlayRecords.addAll(dataList);
        roomPlayRecord.put(roomNo,userPlayRecords );
    }

    /**
     * 更新回合记录
     *
     * @param req
     * @param playerList
     */
    public static void update(CalCreditParamReq req, List<Player> playerList) {
        List<UserPlayRecord> userPlayRecords = getPlayRecord(req);
        Map<String, UserPlayRecord> userPlayRecordMap = MyStreamUtils.cosMap(userPlayRecords, UserPlayRecord::getUserId);
        for (Player player : playerList) {
            UserPlayRecord userPlayRecord = userPlayRecordMap.get(player.getUser().getId());
            userPlayRecord.setAfterCredit(player.getScore());
            userPlayRecord.setRoundGetCredit(player.getScore() - userPlayRecord.getCurrentCredit());
            userPlayRecordMap.put(userPlayRecord.getUserId(), userPlayRecord);
        }

    }

    /**
     * 获取回合信息
     *
     * @param req
     * @return
     */
    public static List<UserPlayRecord> getPlayRecord(CalCreditParamReq req) {
        List<UserPlayRecord> userPlayRecords = Optional.ofNullable(roomPlayRecord.get(req.getRoomNo())).orElse(new ArrayList<>());
        if (StrUtil.isBlank(req.getRoundNo())) {
            return userPlayRecords;
        }
        return MyStreamUtils.filter(userPlayRecords, e -> e.getRoundNo().equals(req.getRoundNo()));
    }

    /**
     * 获取回合信息
     *
     * @param req
     * @return
     */
    public static List<UserPlayRecordResp> getPlayRecordResp(CalCreditParamReq req) {
        List<UserPlayRecordResp> result = new ArrayList<>();
        List<UserPlayRecord> playRecord = getPlayRecord(req);
        Map<String, List<UserPlayRecord>> collect = playRecord.stream().collect(Collectors.groupingBy(UserPlayRecord::getRoundNo));
        Set<Map.Entry<String, List<UserPlayRecord>>> entries = collect.entrySet();

        for (Map.Entry<String, List<UserPlayRecord>> entry : entries) {
            UserPlayRecordResp userPlayRecordResp = new UserPlayRecordResp();
            userPlayRecordResp.setRoundNo(entry.getKey());
            userPlayRecordResp.setUserPlayRecordList(entry.getValue());
            result.add(userPlayRecordResp);
        }
        result.sort((o1, o2) -> o2.getRoundNo().compareTo(o1.getRoundNo()));
        return result;
    }
}
